package com.di.base.service.Impl;

import com.di.base.Entity.Account;
import com.di.base.mapper.AccountMapper;
import com.di.base.service.AccountService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Slf4j
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountMapper accountMapper;

    @Transactional(rollbackFor = Exception.class)
    public void debit(String userId, BigDecimal amount) {
        log.info("账户服务当前XID: {}", RootContext.getXID());
        Account account = accountMapper.findByUserId(userId);
        if (account == null) {
            throw new RuntimeException("账户不存在");
        }
        if (account.getBalance().compareTo(amount) < 0) {
            throw new RuntimeException("余额不足");
        }
        account.setBalance(account.getBalance().subtract(amount));
        int rows = accountMapper.update(account);
        if (rows != 1) {
            throw new RuntimeException("账户更新失败");
        }
        throw new RuntimeException();
    }
}
